import {create} from "zustand";
import {immer} from 'zustand/middleware/immer'
import {devtools, persist} from 'zustand/middleware'
import {formatMenuTree, getFlatMenuList} from "@/router/helper/generateRouter";
import type {useMenuStoreType, useSettersStoreType} from "@/typings/store";
import {type RouteObjectType} from "@/typings/router";


const initialState: useMenuStoreType.stateType = {
    flatMenuList: [],
    menuList: [],
    menuTree: [],
    collapsed: false
}
const actions = (set: useSettersStoreType<useMenuStoreType.storeType>) => {

    const setAuthMenuList = (menuList: RouteObjectType[]) => {
        set((state: useMenuStoreType.stateType) => {
            state.menuList = menuList
            state.menuTree = formatMenuTree(menuList)
            state.flatMenuList = getFlatMenuList(menuList)
        })
    }
    const setCollapsed = (collapsed: boolean) => {
        set((state: useMenuStoreType.stateType) => {
            state.collapsed = collapsed
        })
    }
    const clearAuthMenu = () => {
        set((state: useMenuStoreType.stateType) => {
            state.flatMenuList = []
            state.menuList = []
            state.menuTree = []
        })
    }

    return {setAuthMenuList, setCollapsed, clearAuthMenu}
}

const storage = {name: 'menu-storage'}
export const useMenuStore = create<useMenuStoreType.storeType>()(devtools(persist(immer((set) => ({
    ...initialState,
    ...actions(set)
})), {...storage, partialize: (state) => ({collapsed: state.collapsed})}), storage))

